<template>
  <div class="p-3 flex">
    <div class="w-15/20 flex">
      <div class="w-1/2">
        <div class="flex" ref="myCard">
          <div class="w-1/2 m-1 h-full"><CardShow :card-data="tenantData" /></div>
          <div class="w-1/2 m-1 h-full"><CardShow :card-data="allocation" /></div>
        </div>
        <div class="flex">
          <div class="w-1/4 m-1"><CardShow :card-data="deviceData" /></div>
          <div class="w-1/4 m-1"><CardShow :card-data="assetData" /></div>
          <div class="w-1/4 m-1"><CardShow :card-data="userData" /></div>
          <div class="w-1/4 m-1"><CardShow :card-data="customerData" /></div>
        </div>
        <div class="m-1"><UsageCard :datalist="documentData" /></div>
        <div class="m-1"><UsageCard :datalist="configurationFunctions" /></div>
      </div>
      <div class="w-1/2">
        <div class="flex">
          <div class="w-1/3 m-1"><CardShow :card-data="cpuData" /></div>
          <div class="w-1/3 m-1"><CardShow :card-data="memoryData" /></div>
          <div class="w-1/3 m-1"><CardShow :card-data="diskData" /></div>
        </div>
        <div class="m-1"><EchartsCard :echarts-list="echartsList" /></div>
        <div class="m-1"><MsgEchartsCard :echarts-list="msgEchartsList" /></div>
        <div class="m-1 flex-1"><CardShow :card-data="versionData" /></div>
      </div>
    </div>
    <div class="w-5/20"><StartUsingCard /> </div>
  </div>
</template>

<script setup lang="ts">
  import StartUsingCard from './StartUsingCard.vue';
  import MsgEchartsCard from './MsgEchartsCard.vue';
  import UsageCard from './UsageCard.vue';
  import CardShow from './CardShow.vue';
  import EchartsCard from './EchartsCard.vue';
  import { ref, onMounted, Ref, onBeforeUnmount } from 'vue';
  import { bitToGbit } from './props';
  import dayjs from 'dayjs';
  import { useWebsocketStoreWithOut } from '/@/store/modules/thingsboard/websocket';

  const ws = useWebsocketStoreWithOut();
  let tenantData = ref<any>({
    title: '租户',
    go: true,
    addText: '添加租户',
    icon: '',
    type: 'number',
    value: '343',
    unit: {
      flag: false,
      tip: '',
      text: '',
    },
  });
  let allocation = ref<any>({
    title: '租户配置',
    go: true,
    addText: '添加配置',
    value: '43',
    icon: '',
    type: 'number',
    unit: {
      flag: false,
      tip: '',
      text: '',
    },
  });
  let cpuData = ref<any>({
    title: 'cpu',
    go: false,
    addText: '',
    value: '4%',
    icon: 'ic:baseline-check',
    type: 'number',
    unit: {
      flag: true,
      tip: '7 / 100%',
      text: '| 8 cores',
    },
  });
  let memoryData = ref<any>({
    title: '内存',
    go: false,
    addText: '',
    value: '87%',
    icon: 'solar:danger-triangle-bold',
    type: 'number',
    unit: {
      flag: true,
      tip: '7 / 100%',
      text: '| 16 Gb',
    },
  });
  let diskData = ref<any>({
    title: '磁盘',
    go: false,
    addText: '',
    value: '64%',
    icon: 'ic:baseline-check',
    type: 'number',
    unit: {
      flag: true,
      tip: '7 / 100%',
      text: '| 50 Gb',
    },
  });
  let deviceData = ref<any>({
    title: '设备',
    go: false,
    addText: '',
    value: '734',
    icon: '',
    type: 'number',
    unit: {
      flag: false,
      tip: '',
      text: '',
    },
  });
  let assetData = ref<any>({
    title: '资产',
    go: false,
    addText: '',
    value: '34',
    icon: '',
    type: 'number',
    unit: {
      flag: false,
      tip: '',
      text: '',
    },
  });
  let userData = ref<any>({
    title: '用户',
    go: false,
    addText: '',
    value: '4',
    icon: '',
    type: 'number',
    unit: {
      flag: false,
      tip: '',
      text: '',
    },
  });
  let customerData = ref<any>({
    title: '客户',
    go: false,
    addText: '',
    value: '4',
    icon: '',
    type: 'number',
    unit: {
      flag: false,
      tip: '',
      text: '',
    },
  });
  let documentData = ref<any>({
    name: '文档',
    canGo: false,
    canEdit: true,
    ant: 2,
  });
  let configurationFunctions = ref<any>({
    name: '配置的功能',
    canGo: false,
    ant: 4,
  });
  let versionData = ref<any>({
    title: '版本',
    go: false,
    addText: '联系我们',
    value: {
      version: '3.6.1',
    },
    icon: '',
    type: 'version',
    unit: {
      flag: false,
      tip: '',
      text: '',
    },
  });

  let echartsList = ref<Array<any>>([
    {
      title: 'CPU',
      data: [],
    },
    {
      title: '内存',
      data: [],
    },
    {
      title: '磁盘',
      data: [],
    },
  ]);
  let msgEchartsList = ref<Array<any>>([]);
  const myCard: Ref<HTMLElement | null> = ref(null);

  // 获取租户、租户配置、设备、资产、用户、客户数量
  const handleGetData1 = () => {
    let sendMsg = {
      entityDataCmds: [
        {
          query: {
            entityFilter: {
              type: 'apiUsageState',
              resolveMultiple: true,
            },
            pageLink: {
              page: 0,
              pageSize: 1024,
              textSearch: null,
              dynamic: true,
            },
            entityFields: [
              {
                type: 'ENTITY_FIELD',
                key: 'name',
              },
              {
                type: 'ENTITY_FIELD',
                key: 'label',
              },
              {
                type: 'ENTITY_FIELD',
                key: 'additionalInfo',
              },
            ],
            latestValues: [
              {
                type: 'TIME_SERIES',
                key: 'clusterMode',
              },
            ],
          },
          latestCmd: {
            keys: [
              {
                type: 'TIME_SERIES',
                key: 'clusterMode',
              },
            ],
          },
          cmdId: ws.getAndIncrementCmdId(),
        },
      ],
      entityCountCmds: [
        {
          query: {
            entityFilter: {
              type: 'entityType',
              resolveMultiple: true,
              entityType: 'TENANT',
            },
          },
          cmdId: ws.getAndIncrementCmdId(),
        },
        {
          query: {
            entityFilter: {
              type: 'entityType',
              resolveMultiple: true,
              entityType: 'TENANT_PROFILE',
            },
          },
          cmdId: ws.getAndIncrementCmdId(),
        },
        {
          query: {
            entityFilter: {
              type: 'entityType',
              resolveMultiple: true,
              entityType: 'DEVICE',
            },
          },
          cmdId: ws.getAndIncrementCmdId(),
        },
        {
          query: {
            entityFilter: {
              type: 'entityType',
              resolveMultiple: true,
              entityType: 'ASSET',
            },
          },
          cmdId: ws.getAndIncrementCmdId(),
        },
        {
          query: {
            entityFilter: {
              type: 'entityType',
              resolveMultiple: true,
              entityType: 'USER',
            },
          },
          cmdId: ws.getAndIncrementCmdId(),
        },
        {
          query: {
            entityFilter: {
              type: 'entityType',
              resolveMultiple: true,
              entityType: 'CUSTOMER',
            },
          },
          cmdId: ws.getAndIncrementCmdId(),
        },
      ],
    };
    const cmdIdArr: number[] = [];
    const cmdId1 = ws.getCmdId;
    for (let i = 0; i < 7; i++) {
      cmdIdArr.unshift(cmdId1 - i);
    }
    ws.send(cmdIdArr, sendMsg, (res) => {
      if (res.cmdUpdateType === 'COUNT_DATA') {
        if (res.cmdId === cmdIdArr[1]) {
          tenantData.value.value = res.count;
        }
        if (res.cmdId === cmdIdArr[2]) {
          allocation.value.value = res.count;
        }
        if (res.cmdId === cmdIdArr[3]) {
          deviceData.value.value = res.count;
        }
        if (res.cmdId === cmdIdArr[4]) {
          assetData.value.value = res.count;
        }
        if (res.cmdId === cmdIdArr[5]) {
          userData.value.value = res.count;
        }
        if (res.cmdId === cmdIdArr[6]) {
          customerData.value.value = res.count;
        }
      }
    });
  };

  // 传输消息chart数据
  const handleGetData2 = () => {
    let sendMsg1 = {
      entityDataCmds: [
        {
          query: {
            entityFilter: {
              type: 'apiUsageState',
              resolveMultiple: true,
            },
            pageLink: {
              pageSize: 1024,
              page: 0,
              sortOrder: {
                key: {
                  type: 'ENTITY_FIELD',
                  key: 'createdTime',
                },
                direction: 'DESC',
              },
            },
            entityFields: [
              {
                type: 'ENTITY_FIELD',
                key: 'name',
              },
              {
                type: 'ENTITY_FIELD',
                key: 'label',
              },
              {
                type: 'ENTITY_FIELD',
                key: 'additionalInfo',
              },
            ],
            latestValues: [],
          },
          cmdId: ws.getAndIncrementCmdId(),
        },
      ],
    };
    ws.send(ws.getCmdId, sendMsg1);
    let sendMsg2 = {
      entityDataCmds: [
        {
          cmdId: ws.getCmdId,
          historyCmd: {
            keys: ['transportMsgCountHourly'],
            startTs: new Date().getTime() - 30 * 24 * 60 * 60 * 1000,
            endTs: new Date().getTime(),
            interval: 24 * 60 * 60 * 1000,
            limit: 30,
            agg: 'SUM',
          },
        },
      ],
    };
    ws.send(ws.getCmdId, sendMsg2, (res) => {
      if (!!res.update) {
        res.update[0].timeseries.transportMsgCountHourly.forEach((item) => {
          msgEchartsList.value.push([dayjs(item.ts).format('YYYY-MM-DD HH:mm:ss'), item.value]);
        });
      }
    });
  };

  // cpu、内存、磁盘 chart数据
  const handleGetData3 = () => {
    let sendMsg1 = {
      entityDataCmds: [
        {
          query: {
            entityFilter: {
              type: 'apiUsageState',
              resolveMultiple: true,
            },
            pageLink: {
              pageSize: 1024,
              page: 0,
              sortOrder: {
                key: {
                  type: 'ENTITY_FIELD',
                  key: 'createdTime',
                },
                direction: 'DESC',
              },
            },
            entityFields: [
              {
                type: 'ENTITY_FIELD',
                key: 'name',
              },
              {
                type: 'ENTITY_FIELD',
                key: 'label',
              },
              {
                type: 'ENTITY_FIELD',
                key: 'additionalInfo',
              },
            ],
            latestValues: [],
          },
          cmdId: ws.getAndIncrementCmdId(),
        },
      ],
    };
    ws.send(ws.getCmdId, sendMsg1);
    let sendMsg2 = {
      entityDataCmds: [
        {
          cmdId: ws.getCmdId,
          historyCmd: {
            keys: ['cpuUsage', 'memoryUsage', 'discUsage'],
            startTs: new Date().getTime() - 30 * 24 * 60 * 60 * 1000,
            endTs: new Date().getTime(),
            interval: 24 * 60 * 60 * 1000,
            limit: 30,
            agg: 'AVG',
          },
        },
      ],
    };
    ws.send(ws.getCmdId, sendMsg2, (res) => {
      if (!!res.update) {
        Object.keys(res.update[0].timeseries).forEach((keys) => {
          if (keys === 'cpuUsage') {
            res.update[0].timeseries[keys].forEach((item) => {
              echartsList.value[0].data.push([
                dayjs(item.ts).format('YYYY-MM-DD HH:mm:ss'),
                item.value,
              ]);
            });
          }
          if (keys === 'memoryUsage') {
            res.update[0].timeseries[keys].forEach((item) => {
              echartsList.value[1].data.push([
                dayjs(item.ts).format('YYYY-MM-DD HH:mm:ss'),
                item.value,
              ]);
            });
          }
          if (keys === 'discUsage') {
            res.update[0].timeseries[keys].forEach((item) => {
              echartsList.value[2].data.push([
                dayjs(item.ts).format('YYYY-MM-DD HH:mm:ss'),
                item.value,
              ]);
            });
          }
        });
      }
    });
  };

  // cpu、内存、磁盘 usage数据
  const handleGetData4 = () => {
    let sendMsg = {
      entityDataCmds: [
        {
          query: {
            entityFilter: {
              type: 'apiUsageState',
              resolveMultiple: true,
            },
            pageLink: {
              page: 0,
              pageSize: 1024,
              textSearch: null,
              dynamic: true,
            },
            entityFields: [
              {
                type: 'ENTITY_FIELD',
                key: 'name',
              },
              {
                type: 'ENTITY_FIELD',
                key: 'label',
              },
              {
                type: 'ENTITY_FIELD',
                key: 'additionalInfo',
              },
            ],
            latestValues: [
              {
                type: 'TIME_SERIES',
                key: 'cpuUsage',
              },
              {
                type: 'TIME_SERIES',
                key: 'cpuCount',
              },
              {
                type: 'TIME_SERIES',
                key: 'cpuUsage',
              },
              {
                type: 'TIME_SERIES',
                key: 'cpuUsage',
              },
              {
                type: 'TIME_SERIES',
                key: 'memoryUsage',
              },
              {
                type: 'TIME_SERIES',
                key: 'totalMemory',
              },
              {
                type: 'TIME_SERIES',
                key: 'memoryUsage',
              },
              {
                type: 'TIME_SERIES',
                key: 'memoryUsage',
              },
              {
                type: 'TIME_SERIES',
                key: 'discUsage',
              },
              {
                type: 'TIME_SERIES',
                key: 'totalDiscSpace',
              },
              {
                type: 'TIME_SERIES',
                key: 'discUsage',
              },
              {
                type: 'TIME_SERIES',
                key: 'discUsage',
              },
            ],
          },
          latestCmd: {
            keys: [
              {
                type: 'TIME_SERIES',
                key: 'cpuUsage',
              },
              {
                type: 'TIME_SERIES',
                key: 'cpuCount',
              },
              {
                type: 'TIME_SERIES',
                key: 'cpuUsage',
              },
              {
                type: 'TIME_SERIES',
                key: 'cpuUsage',
              },
              {
                type: 'TIME_SERIES',
                key: 'memoryUsage',
              },
              {
                type: 'TIME_SERIES',
                key: 'totalMemory',
              },
              {
                type: 'TIME_SERIES',
                key: 'memoryUsage',
              },
              {
                type: 'TIME_SERIES',
                key: 'memoryUsage',
              },
              {
                type: 'TIME_SERIES',
                key: 'discUsage',
              },
              {
                type: 'TIME_SERIES',
                key: 'totalDiscSpace',
              },
              {
                type: 'TIME_SERIES',
                key: 'discUsage',
              },
              {
                type: 'TIME_SERIES',
                key: 'discUsage',
              },
            ],
          },
          cmdId: ws.getAndIncrementCmdId(),
        },
      ],
    };
    ws.send(ws.getCmdId, sendMsg, (res) => {
      const { cpuUsage, totalDiscSpace, memoryUsage, totalMemory, discUsage, cpuCount } = res.data
        ? res.data.data[0].latest.TIME_SERIES
        : res.update[0].latest.TIME_SERIES;
      cpuData.value.value = `${cpuUsage.value}%`;
      cpuData.value.unit.text = `| ${cpuCount.value} cores`;
      cpuData.value.unit.tip = `${cpuUsage.value} / 100 %`;

      memoryData.value.value = `${memoryUsage.value}%`;
      memoryData.value.unit.text = `| ${bitToGbit(totalMemory.value)} Gb`;
      memoryData.value.unit.tip = `${bitToGbit(
        (Number(totalMemory.value) * Number(memoryUsage.value)) / 100,
      )} / ${bitToGbit(totalMemory.value)} Gb`;

      diskData.value.value = `${discUsage.value}%`;
      diskData.value.unit.text = `| ${bitToGbit(totalDiscSpace.value)} Gb`;
      diskData.value.unit.tip = `${bitToGbit(
        (Number(totalDiscSpace.value) * Number(discUsage.value)) / 100,
      )} / ${bitToGbit(totalDiscSpace.value)} Gb`;
    });
  };

  onMounted(() => {
    handleGetData1();
    handleGetData2();
    handleGetData3();
    handleGetData4();
  });

  onBeforeUnmount(() => {
    // 断开ws
    ws.close(['telemetry']);
  });
</script>
